package com.yunquan.ohana.ui.weather.search

import android.app.Application
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.viewModelScope
import com.yunquan.ohana.BR
import com.yunquan.ohana.R
import com.yunquan.ohana.base.bus.event.SingleLiveEvent
import com.yunquan.ohana.base.ui.BaseViewModel
import com.yunquan.ohana.db.DBWeatherLocation
import com.yunquan.ohana.entity.LocalLocationModel
import com.yunquan.ohana.entity.Location
import com.yunquan.ohana.entity.UserManager
import com.yunquan.ohana.entity.WeatherHistoryEntity
import com.yunquan.ohana.http.BaseHttp
import com.yunquan.ohana.http.observer.BaseObserver
import com.yunquan.ohana.http.transformer.CommonTransformer
import com.yunquan.ohana.utils.Utils
import io.reactivex.rxjava3.disposables.Disposable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.tatarka.bindingcollectionadapter2.ItemBinding

class WeatherSearchViewModel(application: Application) : BaseViewModel(application) {

    val changeCity = SingleLiveEvent<Location>()

    val cityName = ObservableField<String>()
    val showHistory = ObservableField(true)
    val showNotData = ObservableField(false)
    val notDataTip = ObservableField<String>()

    val cityItems = ObservableArrayList<WeatherSearchItemViewModel>()
    val cityItemBinding = ItemBinding.of<WeatherSearchItemViewModel>(
        BR.wsItemViewModel,
        R.layout.item_weather_search_city
    )

    val historyItems = ObservableArrayList<WeatherSearchHistoryItemViewModel>()
    val historyItemBinding = ItemBinding.of<WeatherSearchHistoryItemViewModel>(
        BR.wshItemViewModel,
        R.layout.item_weather_search_history
    )

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        notDataTip.set(Utils.instance.getString(R.string.no_historical_record))
        localData()
    }

    fun localData() {
        viewModelScope.launch(Dispatchers.IO) {
            val list = DBWeatherLocation.instance.selectAll(
                "user_id = ?",
                arrayOf(UserManager.instance.getUser()?.id.toString())
            )
            withContext(Dispatchers.Main) {
                historyItems.clear()
                list.forEach {
                    historyItems.add(WeatherSearchHistoryItemViewModel(this@WeatherSearchViewModel, it))
                }
                if (list.isNotEmpty()) {
                    showHistory.set(true)
                    showNotData.set(false)
                } else {
                    showHistory.set(false)
                    showNotData.set(true)
                }
            }
        }
    }

    fun searchCity(text: String) {
        viewModelScope.launch(Dispatchers.IO) {
            val oldBean = DBWeatherLocation.instance.selectOne(
                "user_id = ? AND name = ?",
                arrayOf(UserManager.instance.getUser()?.id.toString(),text)
            )
            val bean = LocalLocationModel(
                id = oldBean?.id,
                userId = UserManager.instance.getUser()?.id,
                name = text,
            )
            DBWeatherLocation.instance.saveOrUpdate(bean)
        }
        BaseHttp.api.getCityLookup(text)
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<WeatherHistoryEntity>() {
                override fun onSubscribe(d: Disposable) {
                    super.onSubscribe(d)
                    showLoading()
                }

                override fun onSuccess(result: WeatherHistoryEntity?) {
                    super.onSuccess(result)
                    cityItems.clear()
                    if (result?.location?.isNotEmpty() == true) {
                        result.location!!.forEach {
                            cityItems.add(WeatherSearchItemViewModel(this@WeatherSearchViewModel, it))
                        }
                        showNotData.set(false)
                        showHistory.set(false)
                    } else {
                        showHistory.set(false)
                        showNotData.set(true)
                        notDataTip.set(Utils.instance.getString(R.string.no_address_found))
                    }
                }

                override fun onComplete() {
                    super.onComplete()
                    hideLoading()
                }
            })
    }
}